<template>
  <div class="rules-view">
    <!-- 工具栏 -->
    <rule-toolbar
      v-model:search-keyword="searchKeyword"
      @create="handleCreateRule"
      @refresh="refreshRules"
    />

    <!-- 规则列表 -->
    <div class="content">
          <rule-table
      :rules="filteredRules"
      :loading="rulesStore.loading"
      @edit="handleEditRule"
      @delete="handleDeleteRule"
      @toggle="handleToggleRule"
    />
    </div>

    <!-- 规则配置模态框 -->
    <rule-modal
      v-model:show="showRuleModal"
      :editing-rule="editingRule"
      :saving="saving"
      @save="handleSaveRule"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useMessage } from 'naive-ui';
import { useRulesStore } from '../stores/rules';
import type { Rule } from '../types';
import RuleToolbar from '../components/rules/RuleToolbar.vue';
import RuleTable from '../components/rules/RuleTable.vue';
import RuleModal from '../components/rules/RuleModal.vue';

// Store
const rulesStore = useRulesStore();
const message = useMessage();

// 状态
const searchKeyword = ref('');
const showRuleModal = ref(false);
const editingRule = ref<Rule | null>(null);
const saving = ref(false);

// 过滤后的规则列表
const filteredRules = computed(() => {
  if (!searchKeyword.value) {
    return rulesStore.rules;
  }
  return rulesStore.rules.filter((rule: Rule) => 
    rule.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  );
});

// 刷新规则列表
const refreshRules = async () => {
  try {
    await rulesStore.fetchRules();
  } catch (error) {
    message.error('刷新规则列表失败');
  }
};

// 创建规则
const handleCreateRule = () => {
  editingRule.value = null;
  showRuleModal.value = true;
};

// 编辑规则
const handleEditRule = (rule: Rule) => {
  editingRule.value = rule;
  showRuleModal.value = true;
};

// 删除规则
const handleDeleteRule = async (ruleId: string) => {
  try {
    await rulesStore.deleteRule(ruleId);
    message.success('规则删除成功');
  } catch (error) {
    message.error('规则删除失败');
  }
};

// 切换规则状态
const handleToggleRule = async (ruleId: string, enabled: boolean) => {
  try {
    await rulesStore.updateRule(ruleId, { enabled });
    message.success(`规则已${enabled ? '启用' : '禁用'}`);
  } catch (error) {
    message.error('规则状态更新失败');
  }
};

// 保存规则
const handleSaveRule = async (rule: Partial<Rule>) => {
  saving.value = true;
  try {
    if (rule.id) {
      await rulesStore.updateRule(rule.id, rule);
      message.success('规则更新成功');
    } else {
      await rulesStore.createRule(rule as Omit<Rule, 'id' | 'createdAt' | 'updatedAt'>);
      message.success('规则创建成功');
    }
    showRuleModal.value = false;
  } catch (error) {
    message.error('规则保存失败');
  } finally {
    saving.value = false;
  }
};

// 初始化
refreshRules();
</script>

<style scoped>
.rules-view {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}

.content {
  flex: 1;
  overflow: hidden;
}
</style> 